package com.ericsson.enap.modules.kpi.service.impl;

import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.util.SFtpCarrierUtil;
import com.ericsson.enap.modules.kpi.entity.EnipMeasInfo;
import com.ericsson.enap.modules.kpi.entity.EnipMeasValue;
import com.ericsson.enap.modules.kpi.entity.ImsFiveKpi;
import com.ericsson.enap.modules.kpi.entity.VgcFifKpi;
import com.ericsson.enap.modules.kpi.service.EnipKpiFileProcess;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;

/**
 * NRF类型网元五分钟指标处理
 */
@Component
public class KpiFileProcessNRFFIVEImpl implements EnipKpiFileProcess {

    public List<File> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log,Date date, int delay) {
        return null;
    }

    @Override
    public Map<String, List<File>> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log, Date date) {
        log.info("===================================================  start download Files");
        String lastDownTime = ((VgcFifKpi)imsFiveKpi).getLastDownTime();
        FTPInfoVO ftpInfo = new FTPInfoVO();
        ftpInfo.setHost(imsFiveKpi.getIp4());
        ftpInfo.setUserName(imsFiveKpi.getUsername());
        ftpInfo.setPassword(imsFiveKpi.getPassword());
        ftpInfo.setPath(imsFiveKpi.getDownloadPath());
        ftpInfo.setPort(9022);
        TreeMap<String,List<File>> fileMap = new TreeMap<>();
        List<File> fileList;
        SFtpCarrierUtil sftpCarrier = new SFtpCarrierUtil(ftpInfo, log);
        try {
            sftpCarrier.connect();
            Vector v = sftpCarrier.listFiles(ftpInfo.getPath());
            Collections.sort(v);
            if (v.size() > 0) {
                if(null!=lastDownTime&&!"".equals(lastDownTime)) {
                    Iterator it = v.iterator();
                    while (it.hasNext()) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                        String filename = entry.getFilename();
                        SftpATTRS attrs = entry.getAttrs();
                        if (!attrs.isDir()) {
                            if (filename.length() > 33 && filename.contains("gz")
                                    && (filename.substring(0,14).compareTo(lastDownTime))>0) {
                                int startTime=Integer.parseInt(filename.substring(12,14));
                                int endTime=Integer.parseInt(filename.substring(22,24));
                                if((endTime-startTime)==5||(endTime-startTime)==-55) {
                                    File tempFile = sftpCarrier.downloadFileKpi(ftpInfo.getPath(), filename, localDir, filename);
                                    if (null != tempFile) {
                                        String timeKey = filename.substring(0, 14);
                                        if (fileMap.containsKey(timeKey)) {
                                            fileMap.get(timeKey).add(tempFile);
                                        } else {
                                            fileList = new ArrayList<>();
                                            fileList.add(tempFile);
                                            fileMap.put(timeKey, fileList);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }else{
                    Collections.sort(v,Collections.reverseOrder());
                    Iterator it = v.iterator();
                    while (it.hasNext()) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                        String filename = entry.getFilename();
                        SftpATTRS attrs = entry.getAttrs();
                        if (!attrs.isDir()) {
                            if (filename.length() > 33 && filename.contains("gz")) {
                                int startTime=Integer.parseInt(filename.substring(12,14));
                                int endTime=Integer.parseInt(filename.substring(22,24));
                                if((endTime-startTime)==5||(endTime-startTime)==-55) {
                                    File tempFile = sftpCarrier.downloadFileKpi(ftpInfo.getPath(), filename, localDir, filename);
                                    if (null != tempFile) {
                                        String timeKey = filename.substring(0, 14);
                                        fileList = new ArrayList<>();
                                        fileList.add(tempFile);
                                        fileMap.put(timeKey, fileList);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            sftpCarrier.disconnect();
        }
        return fileMap;
    }

    /**
     * 解析文件
     * @param files
     * @param log
     * @return
     */
    public List<EnipMeasInfo> analysis(List<File> files, Logger log){
        List<EnipMeasInfo> meansInfoList = new ArrayList<>();
        for(File file:files) {
            SAXReader reader = new SAXReader();
            Document doc = null;
            try {
                doc = reader.read(file);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            Element measData = doc.getRootElement().element("measData");
            String beginTime = doc.getRootElement().element("fileHeader").element("measCollec").attributeValue("beginTime");
            beginTime = beginTime.substring(0, beginTime.indexOf("+")).replace("T", " ");
            List<?> measInfoList = measData.elements("measInfo");
            for (Iterator<?> it = measInfoList.iterator(); it.hasNext(); ) {
                EnipMeasInfo mi = new EnipMeasInfo();
                Element measInfo = (Element) it.next();
                String measInfoId = measInfo.attributeValue("measInfoId");

                Element jobNode = measInfo.element("job");
                String jobId = jobNode.attributeValue("jobId");

                List<?> measTypeList = measInfo.elements("measType");
                Map<String, String> mtMap = new HashMap<>();
                for (Iterator<?> mt = measTypeList.iterator(); mt.hasNext(); ) {
                    Element measTypeNode = (Element) mt.next();
                    String p = measTypeNode.attributeValue("p");
                    String text = measTypeNode.getText();
                    mtMap.put(text, p);
                }

                List<?> measValueList = measInfo.elements("measValue");
                for (Iterator<?> mv = measValueList.iterator(); mv.hasNext(); ) {
                    EnipMeasValue measValue = new EnipMeasValue();
                    Element measValueNode = (Element) mv.next();
                    String measObjLdn = measValueNode.attributeValue("measObjLdn");
                    List<?> rList = measValueNode.elements("r");
                    Map<String, String> rMap = new HashMap<>();
                    for (Iterator<?> r = rList.iterator(); r.hasNext(); ) {
                        Element rNode = (Element) r.next();
                        if("".equals(rNode.getText())){
                            rMap.put(rNode.attributeValue("p"), "0");
                        }else {
                            rMap.put(rNode.attributeValue("p"), rNode.getText());
                        }
                    }
                    measValue.setMeasObjLdn(measObjLdn);
                    measValue.setRMap(rMap);
                    Map<String, EnipMeasValue> mvMap = mi.getMeasValueMap();
                    mvMap.put(measObjLdn, measValue);
                }

                mi.setMeasInfoId(measInfoId);
                mi.setJobId(jobId);
                mi.setMeasTypeMap(mtMap);
                mi.setBeginTime(beginTime);
                meansInfoList.add(mi);
            }
        }
        return meansInfoList;
    }

    @Override
    public File download(ImsFiveKpi imsFiveKpi, String localDir, Logger log) {
        return null;
    }

    @Override
    public boolean needUncompress() {
        return true;
    }

    @Override
    public NetType getNetType() {
        return NetType.nrf;
    }
}
